package com.rabbitmq.extension.config;


import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.transaction.RabbitTransactionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitTemplateConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate=new RabbitTemplate(connectionFactory);
        return rabbitTemplate;
    }
//    @Bean
//    public RabbitTemplate confirmRabbitTemplate(ConnectionFactory connectionFactory){
//        RabbitTemplate rabbitTemplate=new RabbitTemplate(connectionFactory);
//
//        //设置回调方法，在配置里面设置，则就不用返回调用啦，同一个接口就可以多次访问啦
//        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
//            @Override
//            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
//                System.out.println("执行了confirm方法");
//                if(ack){
//                    System.out.printf("接受到了消息，消息ID: %s \n",correlationData==null?null:correlationData.getId());
//
//                }else{
//                    System.out.printf("未接受道消息,消息ID: %s, cause: %s \n",correlationData==null?null:correlationData.getId(),cause);
//                }
//
//            }
//        });
//        //消息被退回时，回调方法
//        //这个是针对交换机到队列
//        rabbitTemplate.setMandatory(true);
//        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
//            @Override
//            public void returnedMessage(ReturnedMessage returnedMessage) {
//                System.out.println("消息退回:"+returnedMessage);
//            }
//        });
//        return rabbitTemplate;
//    }

    @Bean("transRabbitTemplate")
    public RabbitTemplate transRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate=new RabbitTemplate(connectionFactory);
        //开启事务
        rabbitTemplate.setChannelTransacted(true);
        return rabbitTemplate;
    }
    @Bean
    public RabbitTransactionManager rabbitTransactionManager(ConnectionFactory connectionFactory){
        return new RabbitTransactionManager(connectionFactory);
    }




}
